<template>
    <div class='attribute'>
        <div class="boxin">
            <div class="boxl">
                <div class="txt txt1">
                    <p class="title">商品属性</p>
                </div>
            </div>
            <div class="boxr">
                <el-form ref="form" :model="form" :rules="rules" label-width="200px" v-loading="loading">
                    <el-col :span="24">
                        <el-col :span="12">
                            <el-form-item label="属性类型" prop="attribute">
                                <el-select v-if="edit" v-model="form.attribute" placeholder="请选择属性类型" filterable clearable>
                                    <el-option v-for="dict in attributeList" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                                </el-select>
                                <span v-else>
                                    {{ selectDictLabel(attributeList, form.attribute) }}
                                </span>
                            </el-form-item>
                        </el-col>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="商品规格" prop="privateGoodsItem">
                            <div class="goods-container" v-for="(attr, index) in privateGoodsItem" :key="index">
                                <div class="goods-content">
                                    <div class="goods-content-box">
                                        <div class="goods-content-left">
                                            <el-form label-width="80px" style="width:400px">
                                                <el-form-item label="规格名">
                                                    <el-input v-if="handleShow == 'add'" v-model="attr.privateSpecName" @keyup.native="textError=''"
                                                        placeholder="请输入规格名">
                                                    </el-input>
                                                    <span v-else>{{attr.privateSpecName}}</span>
                                                </el-form-item>
                                                <el-form-item label="规格值">
                                                    <template v-if="handleShow == 'add'">
                                                        <el-tag v-for="tag in attr.dynamicTags" :key="tag" closable :disable-transitions="false"
                                                            @keyup.native="textError=''" @close="handleClose(tag, attr)">
                                                            {{ tag }}
                                                        </el-tag>
                                                    </template>
                                                    <template v-else>
                                                        <el-tag v-for="tag in attr.dynamicTags" :key="tag">
                                                            {{ tag }}
                                                        </el-tag>
                                                    </template>
                                                    <el-input class="input-new-tag" v-if="attr.inputVisible" v-model="attr.inputValue" :ref="`saveTagInput${index}`"
                                                        size="small" @keyup.enter.native="handleInputConfirm(attr.inputValue, attr)" @blur="handleInputConfirm(attr.inputValue, attr)">
                                                    </el-input>
                                                    <template v-else>
                                                        <el-button v-if="handleShow == 'add'" class="button-new-tag" size="small" @click="showInput(attr, index)">+
                                                            添加
                                                        </el-button>
                                                    </template>
                                                </el-form-item>
                                            </el-form>
                                        </div>
                                        <div class="goods-content-right">
                                            <el-link v-if="handleShow == 'add'" type="danger" @click="delPrivateSpec(index)">删除规格</el-link>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="goods-spec" v-if="handleShow == 'add'">
                                <div class="text-error">{{textError}}</div>
                                <el-link type="primary" @click="addPrivateSpec" class="goods-spec-add">添加规格</el-link>
                            </div>
                            <el-row :gutter="10" class="mb8">
                                <el-col :span="1.5">
                                    <el-button v-if="edit" type="primary" size="mini" @click="batchPrice()">批量修改销售价格</el-button>
                                    <el-button v-if="edit" type="primary" size="mini" @click="batchPrice()">批量修改商品库存</el-button>
                                    <el-button v-if="edit" type="primary" size="mini" @click="batchPrice()">批量修改库存预警值</el-button>
                                </el-col>

                            </el-row>
                            <el-table ref="multipleTable" :data="tableColumnList.tableBodyList" stripe tooltip-effect="dark" style="width: 100%;margin-top:1%;">
                                <el-table-column :label="item.propName" :property="item.prop" v-for="item in tableColumnList.tableHeaderList" :key="item.prop"
                                    align="center">
                                    <template slot-scope="scope">
                                        <span>{{ scope.row[scope.column.property] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="销售价格（元）">
                                    <template slot="header" slot-scope="scope">
                                        <span class="mgrinr1">销售价格（元）</span>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-input v-if="edit" v-model="scope.row.price" @keyup.native="scope.row.price=onInput(scope.row.price)">
                                        </el-input>
                                        <span v-else>{{scope.row.price}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="商品库存">
                                    <template slot="header" slot-scope="scope">
                                        <span class="mgrinr1">商品库存</span>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-input v-if="edit" v-model="scope.row.stock" @keyup.native="scope.row.stock=handleNum(scope.row.stock)">
                                        </el-input>
                                        <span v-else>{{scope.row.stock}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="库存预警值">
                                    <template slot="header" slot-scope="scope">
                                        <span class="mgrinr1">库存预警值</span>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-input v-if="edit" v-model="scope.row.warning" @keyup.native="scope.row.warning=handleNum(scope.row.warning)">
                                        </el-input>
                                        <span v-else>{{scope.row.warning}}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="SKU编号">
                                    <template slot="header" slot-scope="scope">
                                        <span class="mgrinr1">SKU编号</span>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-input v-if="edit" v-model="scope.row.sku">
                                        </el-input>
                                        <span v-else>{{scope.row.sku}}</span>
                                    </template>
                                </el-table-column>

                            </el-table>
                        </el-form-item>
                    </el-col>
                    <el-col :span="18">
                        <el-form-item>
                            <el-descriptions class="margin-top decs" :column="1" :size="size" border>
                                <el-descriptions-item :labelStyle='labelStyle'>
                                    <template slot="label">
                                        参数类型
                                    </template>
                                    <el-col :span="24">
                                        <el-form-item prop="receipt_admin_name">
                                            <span class="p">录入参数</span>
                                        </el-form-item>
                                    </el-col>
                                </el-descriptions-item>
                                <el-descriptions-item :labelStyle='labelStyle'>
                                    <template slot="label">
                                        上市年份
                                    </template>
                                    <el-col :span="24">
                                        <el-form-item prop="year">
                                            <el-date-picker v-model="form.year" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" />
                                        </el-form-item>
                                    </el-col>
                                </el-descriptions-item>
                                <el-descriptions-item :labelStyle='labelStyle'>
                                    <template slot="label">
                                        主材含量
                                    </template>
                                    <el-col :span="24">
                                        <el-form-item prop="material">
                                            <el-input style="width: 220px;" v-model="form.material" placeholder="请输入" />
                                        </el-form-item>
                                    </el-col>
                                </el-descriptions-item>
                                <el-descriptions-item :labelStyle='labelStyle'>
                                    <template slot="label">
                                        适用对象
                                    </template>
                                    <el-col :span="24">
                                        <el-form-item prop="objects">
                                            <el-input style="width: 220px;" v-model="form.objects" placeholder="请输入" />
                                        </el-form-item>
                                    </el-col>
                                </el-descriptions-item>
                            </el-descriptions>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="缩略图" prop="thumbs" v-if="edit">
                            <el-upload list-type="picture-card" :file-list="fileList" :on-change="onchange" :limit="6" :on-exceed="masterFileMax"
                                :class="{ hide: hideUploadBtn }" :action="$uploadUrl" :on-success="(res, file) => handleAvatarSuccess(res, file)"
                                v-if="edit">
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{file}">
                                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                                    <span class="el-upload-list__item-actions">
                                        <span v-if="file.index>0" class="el-upload-list__item-delete" style="font-size: small;" @click="handleFirst(file)">设为首图
                                            <!-- <i class="el-icon-download"></i> -->
                                        </span>
                                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                            <i class="el-icon-zoom-in"></i>
                                        </span>
                                        <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                            <i class="el-icon-delete"></i>
                                        </span>
                                    </span>
                                </div>
                                <div slot="tip" class="el-upload__tip">最多只能上传6张图片</div>
                                <!-- <img v-if="form.thumb" :src="form.avatar" class="avatar"> -->
                                <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                            </el-upload>

                            <el-dialog :visible.sync="dialogVisible" title="图片预览" append-to-body>
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                        </el-form-item>
                        <el-form-item v-else prop="slider" label="缩略图">
                            <el-image v-for="url in form.slider" :key="url" style="width: 150px; height: 150px;border:1px solid #eee;margin-right: 10px;"
                                :src="url" :preview-src-list="[url]">
                            </el-image>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="电脑端详情" prop="detail">
                            <editor v-model="form.detail" placeholder="请输入详情" :height="200" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="移动端详情" prop="detail">
                            <editor v-model="form.detail" placeholder="请输入详情" :height="200" />
                        </el-form-item>
                    </el-col>
                </el-form>
                <div class="button">
                    <el-button @click="$emit('prev')">上一步，选择商品分类</el-button>
                    <el-button type="primary" @click="submit">下一步，填写商品信息</el-button>
                </div>

                <!-- 批量修改 -->
                <el-dialog title="批量修改" :visible.sync="batchShow" width="500px" append-to-body @close="formPrice={};batchShow=false"
                    :close-on-click-modal="false">
                    <el-form ref="formPrice" :model="formPrice" :rules="ruless" label-width="0">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item prop="price">
                                    <el-input v-model="formPrice.price" placeholder="请输入" @keyup.native="formPrice.price=onInput(formPrice.price)" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="formPrice={};batchShow=false">取 消</el-button>
                        <el-button type="primary" @click="submitPrice">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        </div>
    </div>
</template>

<script>
import editor from '@/components/Editor/index'
export default {
    name: 'attribute',
    props: {
        handleShow: {
            type: String, //add新增edit编辑
            default: ""
        },
    },
    components: {
        editor
    },
    data() {
        return {
            loading: false,
            edit: true,
            form: {
                slider: [],
                slider0: '',
            },
            rules: {
                year: [{ required: true, message: '请选择上市年份', trigger: 'change' }],
                material: [{ required: true, message: '请输入主材含量', trigger: 'blur' }],
            },
            attributeList: [
                { dictValue: 1, dictLabel: "属性类型1" },
                { dictValue: 2, dictLabel: "属性类型2" }
            ],
            tableColumnList: {
                tableHeaderList: [],
                tableBodyList: []
            },
            privateGoodsItem: [
                {
                    privateSpecName: '', //规格名
                    dynamicTags: [], //规格值数组
                    inputVisible: false,
                    inputValue: ''
                }
            ],
            batchShow: false,
            formPrice: {
                price: null
            },
            ruless: {
                price: [{ required: true, message: '请输入', trigger: 'change' }],
            },
            textError: '',
            size: 'medium',
            labelStyle: { 'width': '30%', "text-align": "center" },

            hideUploadBtn: false,
            fileList: [],
            picturesList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            limit: '',

        }
    },
    watch: {
        // 监听规格数据
        calculateAttribute(newVal) {
            if (this.handleShow == "add") {
                let cloneNewVal = JSON.parse(JSON.stringify(newVal))
                let attrName = [] //规格名数组
                let attrValue = [] //规格值数组
                for (let key in cloneNewVal) {
                    attrName.push(key)
                    attrValue.push(cloneNewVal[key])
                }
                // 表格内容数据（笛卡尔积算法）
                let finalArr = this.cartesianProductOf(...attrValue)

                let tableObj = {
                    tableBodyList: [],
                    tableHeaderList: []
                }
                // 表格内容
                tableObj.tableBodyList = finalArr.map((item) => {
                    let obj = {
                        price: 0,
                        stock: 0,
                        low_stock: 0,
                        sku: null,
                    }
                    for (let i = 0; i < item.length; i++) {
                        obj[attrName[i]] = item[i]
                    }
                    return obj
                })
                this.tableColumnList.tableBodyList = tableObj.tableBodyList //表格内容数据

                // 表头
                let skuTableArr = Object.keys(newVal)
                tableObj.tableHeaderList = skuTableArr.map((item) => {
                    return {
                        prop: item,
                        propName: item
                    }
                })
                this.tableColumnList.tableHeaderList = tableObj.tableHeaderList // 表头
            }
        }
    },
    computed: {
        // 计算规格
        calculateAttribute() {
            // 初始化
            let obj = {}
            this.privateGoodsItem.forEach((item) => {
                // 判断有没有输入规格名
                if (item.privateSpecName) {
                    //规格名:规格值     //'颜色':'尺寸'
                    obj[item.privateSpecName] = item.dynamicTags
                }
            })
            return obj
        }
    },
    created() {
        this.edit = this.type == "detail" ? false : true
    },
    methods: {
        submit() {
            let fun = [this.$refs.form.validate()]
            fun.push(new Promise((resolve, reject) => {
                this.privateGoodsItem.forEach(e => {
                    if (!e.privateSpecName || e.dynamicTags.length == 0) {
                        this.textError = '请填写商品规格'
                        reject()
                    }
                });
                resolve()
            }))
            Promise.all(fun).then(res => {
                this.$emit('next')
            })
        },
        submitPrice() {
            this.$refs.formPrice.validate((valid) => {
                if (valid) {
                    console.log(this.tableColumnList, 111)
                    this.tableColumnList.tableBodyList.forEach(e => {
                        e.price = this.formPrice.price
                    });
                    this.formPrice = {}
                    this.batchShow = false
                }
            });
        },
        batchPrice() {
            if (this.tableColumnList.tableBodyList.length > 0) {
                this.batchShow = true
            }
        },
        // 添加规格
        addPrivateSpec(index) {
            this.privateGoodsItem.push({
                privateSpecName: '',
                dynamicTags: [],
                inputVisible: false,
                inputValue: ''
            })
        },
        delPrivateSpec(index) {
            this.privateGoodsItem.splice(index, 1)
        },
        handleInputConfirm(val, attr) {
            if (val) {
                attr.dynamicTags.push(val)
            }
            attr.inputVisible = false
            attr.inputValue = ''
        },
        handleClose(tag, item) {
            item.dynamicTags.splice(item.dynamicTags.indexOf(tag), 1)
        },
        showInput(attr, index) {
            attr.inputVisible = true
            this.$nextTick((_) => {
                console.log(this.$refs[`saveTagInput${index}`], 1)
                // this.$refs[`saveTagInput${index}`][0].$refs.input.focus()
            })
        },
        // 笛卡尔积算法
        cartesianProductOf(...args) {
            return args.reduce(
                (total, current) => {
                    let ret = []
                    total.forEach((a) => {
                        current.forEach((b) => {
                            ret.push(a.concat([b]))
                        })
                    })
                    return ret
                },
                [[]]
            )
        },

        // 上传图片
        handleFirst(file, index) {
            console.log(file);
            const objFirst = {
                name: file.name,
                percentage: file.percentage,
                raw: file.raw,
                size: file.size,
                status: file.status,
                uid: file.uid,
                url: file.url,
                index: 0
            }
            console.log(this.fileList, '-----')
            this.fileList.unshift(objFirst)
            var index = this.fileList.indexOf(file)
            if (index !== -1) {
                this.picturesList = this.form.slider
                this.picturesList.unshift(this.picturesList[index - 1])
                this.picturesList.splice(index, 1)
                this.fileList.splice(index, 1)
            }
            console.log(this.picturesList, 'first')
            this.form.slider0 = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider0, "传参")
            this.form.cover = this.picturesList[0]
            this.fileList.forEach((e, index) => {
                if (index > 0) {
                    e.index += 1
                }
            });
            console.log(this.fileList, 788888)
        },
        masterFileMax(files, fileList) {
            // this.$message.warning(`请最多上传 ${this.limit} 个文件。`);
            this.$alert('请删除后再上传', '警告', {
                confirmButtonText: '确定',
                type: 'warning'
            });
        },
        handleAvatarSuccess(res, file) {
            let url = res.data[0].fileurl
            this.fileList.push({
                url: url,
                index: this.fileList.length
            })
            if (this.fileList.length >= 6) {
                this.hideUploadBtn = true
            }
            this.picturesList = this.form.slider
            console.log(this.picturesList, 78999)
            this.picturesList.push(res.data[0].fileurl)
            this.form.slider0 = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            this.form.cover = this.picturesList[0]
        },
        onchange(file, fileList) {
            console.log("上传成功", file, fileList);
            if (this.fileList.length >= 6) {
                this.hideUploadBtn = true
            }
            console.log(this.form.slider, '++++')
            // this.$set(this.form, 'thumbs', fileList)
            this.form.slider0 = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider0, "传参")
            this.form.cover = this.picturesList[0]
        },
        handleRemove(file, fileList) {
            this.picturesList = this.form.slider
            this.picturesList.splice(this.fileList.indexOf(file), 1);
            this.fileList.splice(this.fileList.indexOf(file), 1);
            console.log(this.fileList)
            if (this.fileList.length >= 6) {
                this.hideUploadBtn = true
            } else { this.hideUploadBtn = false }
            console.log(this.picturesList, 'remove')
            this.form.slider0 = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider0, "传参")
            this.form.cover = this.picturesList[0]
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
    },
}

</script>
<style scoped lang='scss'>
.goods-spec {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .goods-spec-add {
        margin-right: 15px;
    }
}

.goods-container {
    .button-new-tag {
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-right: 10px;
        vertical-align: bottom;
    }
    .el-tag {
        margin-right: 10px;
    }
    .goods-content {
        margin-bottom: 10px;
        padding: 14px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        background-color: #fcfcfc;
    }
}
.goods-content {
    .goods-content-box {
        display: flex;
        align-items: center;
        .goods-content-left {
            flex: 1;
        }
    }
}
.decs {
    /deep/.el-descriptions--mini.is-bordered .el-descriptions-item__cell {
        padding: 0 10px;
    }

    /deep/.el-descriptions-item__cell {
        padding-left: 8px;
        font-size: 14px;
    }

    /deep/ .el-col {
        margin: 0px;
        padding: 0px;
        height: 30px;
        line-height: 30px;
    }

    /deep/.el-form-item__error {
        top: 21%;
        right: 5% !important;
        left: unset;
    }
}

/deep/.el-descriptions-item__cell {
    padding: 0;
}

// /deep/ .el-col {
//     margin: 0px;
//     padding: 0px;
//     height: 30px;
//     line-height: 30px;
// }

.p {
    display: block;
    font-size: 12px;
    text-align: center;
}
</style>